

var init_tree = function (config) {

    var Tree = Ext.tree;

    var tree = new Tree.TreePanel({
        useArrows: true,
        autoScroll: true,
        animate: true,
        enableDD: true,
        containerScroll: true,
        border: false,
        // auto create TreeLoader
        dataUrl: config.json_tree_url,

        root: {
            nodeType: 'async',
            text: config.model,
            draggable: false,
            id: 'root'
        },

        tbar: [
        ]


    });


    tree.render('tree-div');

    if (config.rights.add) {
        var b = new Ext.Toolbar.Button({
             text: 'Add',
             id:'bAdd',
             handler: function(){
                 create_form_window(0);
             }
         });
        tree.getTopToolbar().add(b);
    }

    tree.render('tree-div');

    // render the tree
    tree.getRootNode().expand();


    var oldPosition = null;
    var oldNextSibling = null;

    tree.on('startdrag', function(tree, node, event){
        oldPosition = node.parentNode.indexOf(node);
        oldNextSibling = node.nextSibling;
    });

    tree.on('dblclick', function(node, eventobject){
        //node.leaf=false;
    });

    tree.on('movenode', function(tree, node, oldParent, newParent, position){

        if (oldParent == newParent){
            var url = config.json_reorder_url;
            var params = {'node':node.id, 'delta':(position-oldPosition)};
        } else {
            var url = config.json_reparent_url;
            var params = {'node':node.id, 'parent':newParent.id, 'position':position};
        }

        // we disable tree interaction until we've heard a response from the server
        // this prevents concurrent requests which could yield unusual results

        tree.disable();

        Ext.Ajax.request({
            url:url,
            params:params,
            success:function(response, request) {

                // if the first char of our response is zero, then we fail the operation,
                // otherwise we re-enable the tree

                if (response.responseText.charAt(0) != 1){
                    request.failure();
                } else {
                    tree.enable();
                }
            },
            failure:function() {

                // we move the node back to where it was beforehand and
                // we suspendEvents() so that we don't get stuck in a possible infinite loop

                tree.suspendEvents();
                oldParent.appendChild(node);
                if (oldNextSibling){
                    oldParent.insertBefore(node, oldNextSibling);
                }

                tree.resumeEvents();
                tree.enable();

                alert("Oh no! Your changes could not be saved!");
            }

        });

    });



}
